<template>
  <div>
    <!-- 按钮 -->
    <div style="display: flex;align-items: center;margin: -10px 0;">
      <el-button style="margin:10px 10px" type="primary" icon="el-icon-refresh-right" circle
        @click="getPageAccountDetailList"></el-button>
      <!-- 表格
      data 展示数据 —— 数组类型
      <i v-if="circleCheck" style="color: #66ce11;margin-left: 5px;"
          class="el-icon-circle-check"></i>
    -->
      <div style="width: 120px;">
        <el-upload style="margin: 30px 0;" action="#" :before-upload="beforeUpload" :show-file-list="false"
          accept=".xlsx, .xls">
          <el-button slot="trigger" type="primary">导入报表</el-button>
        </el-upload>
      </div>
      <el-button @click="handleExport2" style="margin-right: 30px;">导出报表</el-button>
      <el-date-picker v-model="valueData" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels
        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
      </el-date-picker>
      <el-button style="margin-left: 10px;" icon="el-icon-search" @click="rangeChange"></el-button>
    </div>
    <el-table :height="tableHeight" ref="tableData" id="table" :summary-method="getSummaries" show-summary
      style="width: 100%;" border :data="list">
      <el-table-column prop="id" label="订单id" align="center">
      </el-table-column>
      <el-table-column prop="operateUserNickname" label="用户昵称" align="center">
      </el-table-column>
      <el-table-column label="充值类型" align="center"
        :filters="[{ text: '充值金币', value: '1' }, { text: '购买广告', value: '2' }, { text: '充值会员', value: '3' }, { text: '微信提现', value: '5' },{ text: '支付宝提现', value: '6' } ]"
        :filter-method="filterTag" filter-placement="bottom-end">
        <template slot-scope="{ row, $index }">
          <p v-if="row.operateType == 1">充值金币</p>
          <p v-else-if="row.operateType == 2">购买广告</p>
          <p v-else-if="row.operateType == 3">充值会员</p>
          <p v-else-if="row.operateType == 5">微信提现</p>
          <p v-else-if="row.operateType == 6">支付宝提现</p>
        </template>
      </el-table-column>
      <el-table-column label="支付类型" align="center"
        :filters="[{ text: '支付宝提现', value: '支付宝提现' }, { text: '微信提现', value: '微信提现' }, { text: '支付宝支付', value: '支付宝支付' }, { text: '微信支付', value: '微信支付' }, { text: '苹果支付', value: '苹果支付' } ]"
        :filter-method="filterPayMethod" filter-placement="bottom-end">
        <template slot-scope="{ row, $index }">
          <p v-if="row.payMethod">{{row.payMethod}}</p>
          <p v-else-if="row.operateType == 2 && row.operateMoney == 0">广告金支付</p>
        </template>
      </el-table-column>
      <el-table-column prop="operateMoney" label="金额" align="center">
      </el-table-column>
      <el-table-column prop="commission" label="手续费" align="center">
      </el-table-column>
      <!-- <el-table-column prop="status" label="充值状态" align="center">
      </el-table-column> -->
      <!--      <el-table-column prop="monthNum" label="月数" align="center">
      </el-table-column>
      <el-table-column prop="memberLevel" label="会员等级" align="center">
      </el-table-column> -->
      <el-table-column prop="datOptdt" label="时间" align="center">
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination style="margin-top:20px;textAlign:center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100,100000]"
      :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import XLSX from 'xlsx'
  import {
    exportToExcel
  } from '@/utils/Export2Excel'
  export default {
    name: 'Running',
    data() {
      return {
        tableHeight: 780,
        valueData: [],
        //页码
        pageNumber: 1,
        //每页数量
        pageSize: 10000,
        //总条数
        total: 0,
        //列表数据
        list: [],
        xlsxData: [],
        // circleCheck: localStorage.getItem('sheet')
      }
    },
    created() {
      this.tableHeight = window.innerHeight - 180
    },
    updated() {
      this.$nextTick(() => {
        this.$refs.tableData.doLayout();
      });
    },
    mounted() {

      // 设置表格高度
      this.tableHeight = window.innerHeight - 180
      // / 监听浏览器窗口变化，动态计算表格高度，
      window.onresize = () => {
        return (() => {
          this.tableHeight = window.innerHeight - 180
        })()
      }

      // 获取当前时间
      const today = new Date();
      // 获取当前时间(today)的年份
      const year = today.getFullYear();
      // 获取月份
      const month = String(today.getMonth() + 1).padStart(2, '0');
      // // 获取当前日
      // const day = String(today.getDate()).padStart(2, '0');
      // // 得到年月日
      // const thisDayDate = `${year}-${month}-${day}`; //打印当前日期
      console.log(year, month)
      let ym = year + '-' + month
      this.valueData[0] = ym + '-' + '01'
      this.valueData[1] = ym + '-' + this.getLastDayOfMonth(year, month)
      console.log(this.valueData)
      this.getPageAccountDetailList()
      // console.log(this.round(28.8 + (-30)))
    },
    methods: {
      beforeUpload(file) {
        console.log(file, '--文件');
        this.file2XLSX(file).then((res) => {
          console.log('可以继续对res数据进行二次处理', res[0].sheet)
          localStorage.setItem('sheet', JSON.stringify(res[0].sheet))
          // this.xlsxData = res[0].sheet
          this.$message({
            message: '导入成功',
            type: "success",
            duration: 5 * 1000
          })
          this.getPageAccountDetailList()
        })
        return false
      },
      // excel导入方法
      file2XLSX(file) {
        return new Promise(function(resolve, reject) {
          // 通过FileReader对象读取文件
          const reader = new FileReader()
          // 读取为二进制字符串
          reader.readAsBinaryString(file)
          reader.onload = function(e) {
            console.log(e, '读取文件成功的e');
            // 获取读取文件成功的结果值
            const data = e.target.result
            // XLSX.read解析数据，按照type 的类型解析
            let wb = XLSX.read(data, {
              type: 'binary' // 二进制
            })
            console.log(wb, '---->解析后的数据')
            // 存储获取到的数据
            const result = []
            // 工作表名称的有序列表
            wb.SheetNames.forEach(sheetName => {
              result.push({
                // 工作表名称
                sheetName: sheetName,
                // 利用 sheet_to_json 方法将 excel 转成 json 数据
                sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName])
              })
            })
            resolve(result)
          }
        })
      },





      // 获取某年某月的最后一天
      getLastDayOfMonth(year, month) {
        var date = new Date(year, month - 1, '01');
        //设置日期
        date.setDate(1);
        //设置月份
        date.setMonth(date.getMonth() + 1);
        //获取本月的最后一天
        var cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
        //返回结果
        return cdate.getDate();
      },
      round(num, iCount = 2) {
        // iCount 保留几位小数
        let changeNum = num
        let zs = true
        // 判断是否是负数
        if (changeNum < 0) {
          changeNum = Math.abs(changeNum)
          zs = false
        }
        const iB = Math.pow(10, iCount)
        // 有时乘100结果也不精确
        const value1 = changeNum * iB
        let intDecSet = []
        let intDecHun = []

        let fValue = value1
        const value2 = value1.toString()
        const iDot = value2.indexOf('.')

        // 如果是小数
        if (iDot !== -1) {
          intDecSet = changeNum.toString().split('.')

          // 如果是科学计数法结果
          if (intDecSet[1].indexOf('e') !== -1) {
            return Math.round(value1) / iB
          }
          intDecHun = value2.split('.')

          if (intDecSet[1].length <= iCount) {
            return parseFloat(num, 10)
          }

          const fValue3 = parseInt(intDecSet[1].substring(iCount, iCount + 1), 10)

          if (fValue3 >= 5) {
            fValue = parseInt(intDecHun[0], 10) + 1
          } else {
            // 对于传入的形如111.834999999998 的处理（传入的计算结果就是错误的，应为111.835）
            if (fValue3 === 4 && intDecSet[1].length > 10 && parseInt(intDecSet[1].substring(iCount + 1, iCount + 2),
                10) === 9) {
              fValue = parseInt(intDecHun[0], 10) + 1
            } else {
              fValue = parseInt(intDecHun[0], 10)
            }
          }
        }
        // 如果是负数就用0减四舍五入的绝对值
        let val = zs ? (fValue / iB) : (0 - fValue / iB)

        const d = val.toString().split('.')
        if (d.length === 1) {
          return val.toString() + '.00'
        }
        if (d.length > 1) {
          if (d[1].length < 2) {
            val = val.toString() + '0'
          }
          return val
        }
      },
      rangeChange() {
        console.log('时间范围', this.valueData)
        if (!this.valueData) {
          this.valueData = []
        }
        this.getPageAccountDetailList()
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index === 1) {
            sums[index] = '';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
            sums[index] = this.round(sums[index])
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      handleExport2() {
        let auditResult = prompt('报表名字：');
        if (auditResult != null && auditResult != "") {
          exportToExcel('#table', auditResult);
        }
      },
      addDate(strDate) {
        let dateFormat = new Date(strDate);
        dateFormat = dateFormat.setDate(dateFormat.getDate() + 1);
        dateFormat = new Date(dateFormat);
        let y = dateFormat.getFullYear()
        let m = (dateFormat.getMonth() + 1).toString().padStart(2, '0')
        let d = dateFormat.getDate().toString().padStart(2, '0')
        return `${y}-${m}-${d}`
      },
      async getPageAccountDetailList() {
        let res = await this.$API.running.getPageAccountDetailList({
          pageNumber: this.pageNumber,
          pageSize: this.pageSize,
          endTime: this.addDate(this.valueData[1]),
          startTime: this.valueData[0]
        })
        console.log('充值提现', res.data.rows)
        this.total = res.data.sumLine;

        for (var i = 0; i < res.data.rows.length; i++) {
          if (res.data.rows[i].operateType == 5 || res.data.rows[i].operateType == 6) {
            res.data.rows[i].operateMoney = ~res.data.rows[i].operateMoney + 1
          }
        }
        let xlsxData = JSON.parse(localStorage.getItem('sheet'))
        console.log(xlsxData)
        if (xlsxData) {
          let arr1 = res.data.rows
          let arr2 = xlsxData
          var mergedArr = arr1.map(item1 => {
            const item2 = arr2.find(item2 => item2.id === item1.id);
            return item2 ? {
              ...item1,
              ...item2
            } : item1;
          });
          console.log('组合后1', mergedArr)
          // mergedArr = mergedArr.filter((item) => {
          //   return item.operateUserNickname != ''
          // })
          // console.log('组合后2', mergedArr)
          this.list = mergedArr;
        } else {
          this.list = res.data.rows;
        }
      },
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.pageSize = val
        this.getPageAccountDetailList()
      },
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pageNumber = val
        this.getPageAccountDetailList()
      },
      filterTag(value, row) {
        console.log(value, row)
        return row.operateType == value;
      },
      filterPayMethod(value, row) {
        console.log(value, row)
        return row.payMethod == value;
      },
    }
  }
</script>

<style scoped>
  .el-table {
    overflow: visible !important;
  }
</style>